<?php
    /* Fingon 2011.07 */
    require_once('global.php');
    require_once('/code/Include/db_mysql.php');

    Class Artist
    {
        protected $db;

        public function Artist()    {
            $this->db=new DB();
        }

        public function getArtists($only_active=1, $sort='order by `is_active` DESC, `name`'){
            $sql='select *, (select count(*) from product where product.artist_id=artist.artist_id) as item_count from `artist`'.($only_active?' where `is_active`=1':'').' '.$sort;
            return $this->db->get_rows($sql);
        }
        
        public function getFirstArtistId($sort='order by is_active DESC, name'){
            $sql='select artist_id from `artist`'.' '.$sort.' limit 0,1';
            $rs=$this->db->get_one($sql);
            return empty($rs['artist_id'])? -1 : $rs['artist_id'];
        }

        public function editArtist($a){
            $a=$this->db->override_magic_quotes($a);
            $sql=sprintf('update `artist` set `name`=\'%s\', `is_active`='.$a['is_active'].' where artist_id='.$a['artist_id'], mysql_real_escape_string($a['name']));
            return $this->db->update($sql);
        }

        public function addArtist($a){
            $a=$this->db->override_magic_quotes($a);
            $sql=sprintf('insert into `artist` (`name`, `is_active`, `create_time`) values (\'%s\', '.$a['is_active'].', now())', mysql_real_escape_string($a['name']));
            return $this->db->update($sql);            
        }

        public function deleteArtist($aid){
            if($this->artistItemCount($aid)!=0) return -1;
            $sql='delete from `artist` where artist_id='.$aid;
            $this->db->update($sql);
            return $this->db->affected_rows();
        }

        private function artistItemCount($aid){
            $sql='select count(*) as item_count from product where artist_id='.$aid;
            $rs=$this->db->get_one($sql);
            return intval($rs['item_count']);
        }
    }
?>
